package com.spirit.dcs.idempotent.service.impl;

import com.spirit.dcs.idempotent.entity.OrderState;
import com.spirit.dcs.idempotent.entity.StateRecord;
import com.spirit.dcs.idempotent.mapper.OrderStateMapper;
import com.spirit.dcs.idempotent.mapper.StateRecordMapper;
import com.spirit.dcs.idempotent.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="eric_zheng@lanzuo.com.cn">eric</a>
 * @version 1.0.0
 * Description: 订单相关接口
 * <p>
 * 实际开发中，经常会面对订单支付问题，基本流程如下：
 * ====================================
 * |1. 客户端发起订单支付请求 ；
 * |2. 支付前系统本地相关业务处理 ；
 * |3. 请求第三方支付服务执行扣款；
 * |4. 第三方支付返回处理结果；
 * |5. 本地服务基于支付结果响应客户端；
 * ====================================
 * 根据以上逻辑设计幂等接口
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    StateRecordMapper stateRecordMapper;

    @Resource
    OrderStateMapper orderStateMapper;

    @Override
    public OrderState queryOrder(OrderState orderState) {
        Map<String, Object> params = new HashMap<>();
        params.put("order_id", orderState.getOrderId());

        List<OrderState> orderStateList = orderStateMapper.selectByMap(params);
        if (orderStateList != null && orderStateList.size() > 0) {
            return orderStateList.get(0);
        }

        return null;
    }

    @Override
    public boolean createOrder(OrderState orderState) {
        int saveRes = orderStateMapper.insert(orderState);
        if (saveRes > 0) {
            saveStateRecord(orderState.getOrderId(), "订单创建成功");
        }
        return saveRes > 0;
    }

    @Override
    public boolean localBiz(OrderState orderState) {
        orderState.setState(2);
        int updateRes = orderStateMapper.updateState(orderState);
        if (updateRes > 0) {
            saveStateRecord(orderState.getOrderId(), "本地业务成功");
        }
        return updateRes > 0;
    }

    @Override
    public boolean paymentBiz(OrderState orderState) {
        orderState.setState(3);
        int updateRes = orderStateMapper.updateState(orderState);
        if (updateRes > 0) {
            saveStateRecord(orderState.getOrderId(), "支付业务成功");
        }
        return updateRes > 0;
    }

    /**
     * @param orderState
     * @return
     */
    @Override
    public boolean queryToken(OrderState orderState) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("order_id", orderState.getOrderId());
        paramMap.put("token_id", orderState.getTokenId());
        List<OrderState> orderStateList = orderStateMapper.selectByMap(paramMap);
        return orderStateList.size() > 0;
    }

    private void saveStateRecord(Long orderId, String stateDec) {
        StateRecord stateRecord = new StateRecord();
        stateRecord.setOrderId(orderId);
        stateRecord.setStateDec(stateDec);
        stateRecordMapper.insert(stateRecord);
    }
}
